package net.asfun.jvalog.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.asfun.jvalog.domain.Link;
import net.asfun.jvalog.http.RequestUtil;
import net.asfun.jvalog.view.PagerInfo;

public class RollAction extends BaseAction{
	
	public void index(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		int page = RequestUtil.getIntParam(req, "page");
		PagerInfo pager = new PagerInfo();
		pager.setIndex(page);
		this.assign("links", Link.listAll(pager));
		this.assign("pager", pager);
		this.render("admin/links.html", resp);
	}
	
	public void create(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		this.render("admin/link.html", resp);
	}
	
	public void add(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		String title = RequestUtil.getRequiredParam(req, "title");
		String url = RequestUtil.getRequiredParam(req, "url");
		String image = RequestUtil.getStringParam(req, "image");
		String desc = RequestUtil.getStringParam(req, "description");
		int flag = RequestUtil.getIntParam(req, "flag");
		Link link = new Link();
		link.setTitle(title);
		link.setUrl(url);
		link.setImage(image);
		link.setDescription(desc);
		link.setFlag(flag);
		link.save();
		this.feedback("roll.add", req, resp);
	}
	
	public void delete(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		Long[] ids = RequestUtil.getLongParams(req, "id");
		for(int i=0; i<ids.length; i++) {
			Link.remove(ids[i]);
		}
		this.feedback("roll.delete", req, resp);
		
	}
	
	public void edit(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		Long id = RequestUtil.getLongParam(req, "id");
		this.assign("link", Link.load(id));
		this.render("admin/link.html", resp);
	}
	
	public void update(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		Long id = RequestUtil.getLongParam(req, "id");
		String title = RequestUtil.getRequiredParam(req, "title");
		String url = RequestUtil.getRequiredParam(req, "url");
		String image = RequestUtil.getStringParam(req, "image");
		String desc = RequestUtil.getStringParam(req, "description");
		int flag = RequestUtil.getIntParam(req, "flag");
		Link link = Link.load(id);
		link.setTitle(title);
		link.setUrl(url);
		link.setImage(image);
		link.setDescription(desc);
		link.setFlag(flag);
		link.update();
		this.feedback("roll.update", req, resp);
	}
}
